const amqp = require('amqplib/callback_api');

const URL = "iot.mq.rabbit.ztn-tech.com"
const PORT = 5672
const USER_NAME = "test"
const PASSWORD = "Ztn654321"
const EXCHANGE_NAME = "ztn.iot.sdk"
const QUEUE_BASE_NAME = "."
const IS_DURABLE = true

export function consumer(topic, msgHandler) {
    const queueName = QUEUE_BASE_NAME + topic;
    amqp.connect(`amqp://${USER_NAME}:${PASSWORD}@${URL}:${PORT}`, function (err, conn) {
        const ok = conn.createChannel(on_open);
        function on_open(err, ch) {
            if (err != null) {
                throw new Error(err);
            }
            ch.assertExchange(EXCHANGE_NAME, "topic", { durable: true }).then(function (ex) {
                ch.assertQueue(topic, { durable: IS_DURABLE, exclusive: false, autoDelete: !IS_DURABLE }).then(function (q) {
                    ch.bindQueue(q.queue, ex.exchange, topic);
                    ch.consume(q.queue, function (msg) {
                        if (msg !== null) {
                            console.log('consumer', msg);
                            msgHandler(msg.content.toString());
                            ch.ack(msg);
                        }
                    });
                });
            });
        }
    });
}
